﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Management;
using System.Management.Instrumentation;

namespace LDriver.Providers
{
    public class RS232 : ICommunicationProvider
    {

        private SerialPort sp;

        // Evento scatenato dal prodiver quando ricevere dati in input
        public event DataReceivedEventHandler DataReceived;

        public static string[] PortsList()
        {
            return SerialPort.GetPortNames();
        }

        public RS232(string ComPort, int BaudRate, Parity Parity)
        {
            if (sp != null)
            {
                if (sp.IsOpen) sp.Close();
                sp.Dispose();
            }

            sp = new SerialPort(ComPort, BaudRate, Parity);
            sp.DataReceived += spDataReceived;
        }

        public bool IsOpen()
        {
            return sp.IsOpen;
        }

        public void Close()
        {
            if (sp.IsOpen)
                sp.Close();
        }


        public void SendData(Command dataCommand)
        {
            //if (!sp.IsOpen)
            {
                try
                {
                    sp.Open();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            // Send command
            sp.DiscardOutBuffer();
            sp.DiscardInBuffer();
            sp.Write(dataCommand.CommandBytes, 0, dataCommand.CommandBytes.Length);

        }

        private void spDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int count = sp.BytesToRead; 
            byte[] IncomingData = new byte[count];
            for (int i = 0; i < count; i++)
            {
                if(sp.IsOpen)
                    IncomingData[i] = (byte) sp.ReadByte();
            }
            DataReceived(this, IncomingData);

        }

    }

}
